package com.xiaojie.core;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.ApplicationContext;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

/**
 * @ClassName SpringbootApplication
 * @Author 廖杰
 * @Date 2021/6/15 22:42
 **/
public class SpringbootApplication {

    private static Integer port = 1998;

    public static ApplicationContext run(Class<?> loadClass, String[] args) {

        // 自动配置
        // 加载配置文件 application.properties
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = loadClass.getClassLoader().getResourceAsStream("application.properties");
        // 使用properties对象加载输入流
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Object configPort = properties.get("server.port");
        if (Objects.nonNull(configPort)) {
            port = Integer.valueOf((String)configPort);
        }

        // 启动服务
        Tomcat tomcat = new Tomcat();

        tomcat.setPort(port);

        String baseDir = loadClass.getClassLoader().getResource("").getPath();
        String webappDir = loadClass.getClassLoader().getResource("").getPath();
        tomcat.setBaseDir(baseDir);

        try {
            Context context = tomcat.addWebapp("", webappDir);
            context.getServletContext().setAttribute("loadClass", loadClass);
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException | ServletException e) {
            e.printStackTrace();
        }


        return null;

    }

}
